package com.huajx.mina.tcpserver.codec;

import java.io.Closeable;
import java.io.IOException;
import java.nio.charset.Charset;

import com.huajx.util.StrUtil;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LdEncoderAdapter implements ProtocolEncoder {
	private final static Logger logger = LoggerFactory.getLogger(LdEncoderAdapter.class);
	
	private static final AttributeKey KEY_ENCRYPTOR = new AttributeKey(LdEncoderAdapter.class, "Encryptor");
	private static final AttributeKey KEY_SECRETKEY = new AttributeKey(LdEncoderAdapter.class, "SecretKey");
	private final Charset codePage;
	private final boolean isServer;
	private final boolean isPassiveEncryption;

	public LdEncoderAdapter(Charset charset, boolean isServer, boolean isPassiveEncryption) {
		this.codePage = charset;
		this.isServer = isServer;
		this.isPassiveEncryption = isPassiveEncryption;
	}

	/**
	 * 编码
	 */
	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		String msg = message.toString();
		if (StrUtil.isBlank(msg)) {
			return;
		}
		byte[] source = msg.getBytes(this.codePage);

		String secretKey = (String) session.getAttribute(KEY_SECRETKEY);//密钥
		if (StrUtil.isBlank(secretKey)) {
			logger.debug("no SecretKey,"+msg);
			
//			CharsetEncoder encoder = codePage.newEncoder();
//			IoBuffer io = IoBuffer.allocate(100).setAutoExpand(true);   
//	        io.putString(msg, encoder);   
////	        io.put((byte)'\r');   
////	        io.put((byte)'\n');   
//	        io.flip();   
//	        out.write(io);
			
			out.write(IoBuffer.wrap(source));
		} else if (this.isServer) {
			// SM4 Encryptor = (SM4)getEncryptor(session, SecretKey);
			// byte[] Cipher = Encryptor.TransformFinalBlock(Source, 0,
			// Source.length);
			//
			// IoBuffer Buffer = IoBuffer.allocate(Cipher.length + 4);
			// Buffer.put(Utils.GetBytes(Cipher.length, ByteOrder.BIG_ENDIAN));
			// Buffer.put(Cipher);
			// Buffer.flip();
			// out.write(Buffer);
		} else {
			// Xor64Codec Encryptor = (Xor64Codec)getEncryptor(session,
			// SecretKey);
			// out.write(IoBuffer.wrap(Encryptor.Transform(Source, 0,
			// Source.length)));
		}
	}

	@Override
	public void dispose(IoSession session) throws Exception {
		Closeable Encryptor = (Closeable) session.getAttribute(KEY_ENCRYPTOR);
		if (Encryptor != null) {
			Encryptor.close();
		}
		session.removeAttribute(KEY_ENCRYPTOR);
		session.removeAttribute(KEY_SECRETKEY);
	}

	protected Object getEncryptor(IoSession session, String secretKey) throws IOException {
		Object Encryptor = session.getAttribute(KEY_ENCRYPTOR);
		if (Encryptor == null) {
			if (StrUtil.isNotBlank(secretKey)) {
				if (this.isServer) {
					// Encryptor = new SM4(CipherDirection.Encryption,
					// CipherMode.OFB, PaddingMode.PKCS7);
					//
					// byte[] DerivedVector =
					// SM3.KDF(secretKey.getBytes("UTF-8"), 32);
					// ((SM4)Encryptor).Initialize(Arrays.copyOfRange(DerivedVector,
					// 0, 16), Arrays.copyOfRange(DerivedVector, 16, 32));
				} else {
					// Encryptor = new Xor64Codec(secretKey);
				}
				session.setAttribute(KEY_ENCRYPTOR, Encryptor);
			}
		}
		return Encryptor;
	}

	public Charset getCharset() {
		return this.codePage;
	}

	public boolean getIsServer() {
		return this.isServer;
	}

	public boolean getIsPassiveEncryption() {
		return this.isPassiveEncryption;
	}

	public static void setSecretKey(IoSession session, String key) {
		session.setAttribute(KEY_SECRETKEY, key);
	}

	public static String getSecretKey(IoSession session) {
		return (String) session.getAttribute(KEY_SECRETKEY);
	}
}
